package xiaoqi.qingyue.api.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import xiaoqi.qingyue.api.basic.photo.model.entity.Photo;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author 92110
 */

@Component
public class UploadUtil {
    // 上传文件的目录
    @Value("${file.upload-dir}")
    private String uploadDir;
    @Value("${file.upload-url}")
    private String uploadUrl;

    // 创建目录
    public void init() {
        try {
            Files.createDirectories(Paths.get(uploadDir));
        } catch (IOException e) {
            throw new RuntimeException("无法创建上传目录！", e);
        }
    }

    // 上传文件方法
    public Photo uploadFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        // 检查文件名是否有效
        if (fileName == null || fileName.isEmpty()) {
            throw new RuntimeException("文件名无效！");
        }
        // 获取文件扩展名
        String extension = "";
        int lastIndexOfDot = fileName.lastIndexOf(".");
        if (lastIndexOfDot > 0) {
            // 获取扩展名
            extension = fileName.substring(lastIndexOfDot);
        }

        // 创建新的文件名
        String newFileName = uuid + extension;

        try {
            // 保存文件到指定目录
            Path path = Paths.get(uploadDir, newFileName);
            Files.copy(file.getInputStream(), path);
            // 返回文件的保存路径
            return new Photo(uuid, newFileName, path.toString(), uploadUrl + newFileName);
        } catch (IOException e) {
            System.out.println(e.toString());
            throw new RuntimeException("文件上传失败！", e);

        }
    }

}
